
module TextBlockHandler
  require 'rubygems'
  require 'nokogiri'

  @parser = nil
  @tbh = nil

  class TBH < Nokogiri::XML::SAX::Document

    def initialize(article)
      @article = article
      @blocks = []
      @cur_match = ""
      @cur_word = ""
      @cur_block = nil
      @cur_x = nil
      @cur_y = nil
      @prev_x = nil
      @prev_y = nil
    end

    attr_accessor :blocks

    # get access to Rails logger for debugging
    def logger 
      RAILS_DEFAULT_LOGGER 
    end 

    def start_element(name, attrs = [])
      case name
      when /File/
        return
      when /Block/
        @cur_block = Tblock.new
        @cur_block.article_id = @article.id
        @cur_block.build_nf_rect
        attrs.each_slice(2) do |name, val|
          case name
          when "id"
            @cur_block.tbid = val.to_i
          when "p"
            @cur_block.p = val.to_i
            @cur_block.page_id = @article.pages.find_by_number(@cur_block.p).id
          when "x"
            @cur_block.nf_rect.x = val.to_f
          when "y"
            @cur_block.nf_rect.y = val.to_f
          when "w"
            @cur_block.nf_rect.width = val.to_f
          when "h"
            @cur_block.nf_rect.height = val.to_f
          when "s"
            @cur_block.s = val
          when "sz"
            @cur_block.h = val.to_i
          when "avgH"
            @cur_block.avgh = val.to_i
          when "c"
            @cur_block.classification = val
          when "format"
            @cur_block.format = val
          end
        end
        @blocks << @cur_block
      when /pt/
        @prev_x = @cur_x
        @prev_y = @cur_y if @cur_y
        @cur_x = nil
        @cur_y = nil
        attrs.each_slice(2) do |name, val|
          case name
          when "x"
            @cur_x = val.to_i
          when "y"
            @cur_y = val.to_i
          end
        end
        unless @cur_y
#           word = Word.new
#           word.article_id = @article.id
#           word.nf_rect = NfRect.new
#           word.nf_rect.x = @prev_x
#           word.nf_rect.y = @prev_y
#           word.nf_rect.width = @cur_x - @prev_x
#           word.nf_rect.height = @cur_block.h
#           word.text = @cur_word.dup
#           @cur_block.words << word
        end
        @cur_word = ""

      end
    end

    def characters(value)
      @cur_word += value.strip
    end

  end

  def tbh_new_parser
    # Create a new parser
    @tbh = TBH.new(self)
    @parser = Nokogiri::XML::SAX::Parser.new(@tbh)
  end

  def tbh_parse(file)
    # Feed the parser some XML
    @parser.parse(File.open(file, 'r'))
    @tbh.blocks.each { |tb| tb.save }
  end

  def get_next_auto_increment(table)
    ActiveRecord::Base.connection.execute("SELECT auto_increment " +
                                          "FROM information_schema.tables " +
                                          "WHERE table_name='#{table}'" +
					  "and table_schema='#{DATABASE}'").fetch_hash['auto_increment'].to_i
  end
end
